package com.heyun.controller;

import com.heyun.constant.Constants;
import com.heyun.entity.dto.SignInDTO;
import com.heyun.entity.enums.MyEnum;
import com.heyun.entity.pojo.PointsLog;
import com.heyun.entity.vo.*;
import com.heyun.mapper.StudentMapper;
import com.heyun.result.Result;
import com.heyun.service.StudentService;
import com.heyun.service.TeacherService;
import com.heyun.utils.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Map;
import java.util.Objects;

import static com.heyun.constant.Constants.UPLOAD_DIR;

@RestController
@RequestMapping("/teacher")
@Slf4j
public class TeacherController {

    @Autowired
    private TeacherService teacherService;
    @Autowired
    private StudentService studentService;
    @Autowired
    private ResourceLoader resourceLoader;
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private SimpMessagingTemplate messagingTemplate;

    /**
     * 获取本班的学生信息
     *
     * @param classId
     * @return
     */
    @GetMapping("/getStudentByClass")
    Result getStudents(String classId) {
//        System.out.println(MyEnum.late);
        StudentOfClass[] students = teacherService.getAllStudentByClass(classId);
        if (students.length > 0) {
            log.info(Constants.CLASS_SUCCESS + Arrays.toString(students));
            return Result.success(students);
        } else return Result.error(Constants.CLASS_FAILURE);
    }

    /**
     * 发布作业
     *
     * @param homework
     * @return
     */
    @PutMapping("/putHomeworks")
    Result putHomeworks(@RequestBody Homework homework) {
        int res = teacherService.pubHomeworks(homework);
        if (res == -1)
            return Result.error(Constants.PERMISSION_DENIED + "，" + Constants.PUB_HOMEWORK_FAILURE);
        else if (res == -2)
            return Result.error(Constants.INCOMPLETE_INFORMATION);
        else if (res >= 1)
            return Result.success(Constants.PUB_HOMEWORK_SUCCESS);
        return Result.error(Constants.PUB_HOMEWORK_FAILURE);
    }

    @PutMapping("/putSignIn")
    Result putSignIn(@RequestBody SignIn signIn) {
        SignInDTO res = teacherService.pubSignIn(signIn);
        if (res.getResCode() == -1)
            return Result.error(Constants.PERMISSION_DENIED + "，" + Constants.PUB_SIGN_IN_FAILURE);
        else if (res.getResCode() == -2) {
            return Result.error(Constants.INCOMPLETE_INFORMATION);
        } else if (res.getResCode() >= 1) {
            // 发布签到成功,往所有学生端发送信息
//            System.out.println(signIn.getEndline());
            messagingTemplate.convertAndSend("/topic/signIn", "\"{\"timeEnd\":\""+signIn.getEndline() + "\",\"subjectId\":\"" + signIn.getSubjectId()+"\"}\"");
            return Result.success(res);
        }
        return Result.error(Constants.PUB_SIGN_IN_FAILURE);
    }

    @GetMapping("/getStudentsHomeworks")
    Result getHomeworks() {
        Homework[] hm = teacherService.getHomeworksOfTeacher();
        if (hm != null)
            return Result.success(hm);
        return Result.error(Constants.NULL_HOMEWORK);
    }


    // 定义文件存储路径为项目根目录下的 files 文件夹


    /**
     *  文件上传
     */
    @PostMapping("/upload")
    public Result upload(@RequestParam("file") MultipartFile file,String classId,String context,String homeworkId,LocalDateTime endline,String expId) {
        if (!file.isEmpty()) {
            try {
                // 获取项目根目录路径
                String rootPath = resourceLoader.getResource("classpath:").getFile().getAbsolutePath();
                // 指定文件夹路径
                String uploadDirPath = rootPath + "/files/";
                // 检查并创建目标目录
                File uploadDir = new File(uploadDirPath);
                if (!uploadDir.exists()) {
                    uploadDir.mkdirs(); // 创建多级文件夹
                }
                // 构建文件存储路径
                Map<String, Object> claims = ThreadLocalUtil.get();
                String userId = claims.get("id").toString();
                String roleId = claims.get("role").toString();
                String fileName = file.getOriginalFilename();
                String filePath = uploadDirPath + fileName;
                if (Objects.equals(roleId, "2")) {
                    File destFile = new File(filePath);
                    Homework homework = Homework.builder()
                            .remark(context)
                            .fileName(fileName)
                            .filePath(fileName)
                            .homeworkId(homeworkId)
                            .endline(endline)
                            .userId(userId)
                            .build();
                    int res = teacherService.pubHomeworks(homework);
                    if (res == -1)
                        return Result.error(Constants.PERMISSION_DENIED + "，" + Constants.PUB_SIGN_IN_FAILURE);
                    else if (res == -2) {
                        return Result.error(Constants.INCOMPLETE_INFORMATION);
                    } else if (res >= 1) {
                        file.transferTo(destFile);
                        log.info("文件已保存到路径：" + filePath);
                        return Result.success(homework);
                    }
                } else if (Objects.equals(roleId, "1")) {
                    File destFile = new File(filePath);
                    file.transferTo(destFile);
                    log.info("文件已保存到路径：" + filePath);
                   int res = teacherService.ChangeHomework(expId,fileName);
                   if (res > 0){
                       return Result.success(Constants.UPLOAD_FILE_SUCCESS);
                   }
                } else {
                    log.info("上传文件无法获取用户权限");
                }
            } catch (IOException e) {
                log.error("文件上传失败", e);
                return Result.error("文件上传失败：" + e.getMessage());
            }

        } else {
            return Result.error("请选择要上传的文件");
        }
        return Result.error(Constants.PUB_HOMEWORK_FAILURE);
    }


    /**
     * 批改作业
     * @param homework
     * @return
     */
    @PostMapping("/comments")
    Result pubComments(@RequestBody Homework homework){
        int res = teacherService.CommentStudentHomework(homework);
        if (res == 1){
            log.info("已修改 "+res+" 条成绩信息");
            studentService.addLog(new PointsLog(homework.getUserId(),"平时作业",homework.getGrade(),homework.getSubjectId()));
            int i = studentMapper.updatePoints(homework.getUserId(),homework.getSubjectId(),homework.getGrade());
            return Result.success(Constants.PUB_COMMENTS_SUCCESS);
        }
        return Result.error(Constants.PUB_COMMENTS_FAILURE);
    }


    @GetMapping("/getSubjects")
    Result getSubjects(){
        return Result.success(teacherService.getSubjects());
    }

    @PostMapping("/changeWeight")
    Result changeWeight(@RequestBody SubjectVO subjectVO){
        return Result.success(teacherService.changeWeight(subjectVO));
    }

    @PutMapping("/cancleSignIns")
    Result cancleSignIns(@RequestParam String subjectId){
        return Result.success(teacherService.cancleSignIns(subjectId));
    }
}
